//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/security/CustomAuthenticationManager.java $
//$Id: CustomAuthenticationManager.java 118 2013-04-01 01:11:50Z krieg.maria@gmail.com $
package de.piratech.dasding.security;

import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.Database;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.data.helper.PasswordHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 */
public class CustomAuthenticationManager implements AuthenticationManager {

  private final static Logger LOG = LoggerFactory.getLogger(CustomAuthenticationManager.class);
  @Autowired
  private Database mDatabase;

  @Override
  public Authentication authenticate(Authentication pAuth) throws AuthenticationException {
    try {
      User user = mDatabase.getUserData().getUserByName(pAuth.getName());
      if (StringUtils.equals(PasswordHelper.getCryptedPassword((String) pAuth.getCredentials(), pAuth.getName()), user.getPassword())) {
        LOG.debug("User {} has been authenticated successfully", pAuth.getName());
        return new UsernamePasswordAuthenticationToken(user, pAuth.getCredentials(), pAuth.getAuthorities());
      }
    } catch (DatabaseException dbe) {
      LOG.debug("User " + pAuth.getName() + " could not be loaded", dbe);
    }
    LOG.debug("User {} has failed to authenticate", pAuth.getName());
    throw new BadCredentialsException("Invalid username/password");
  }
}
